package com.jieli.bt.att.ui.settings.log

import androidx.constraintlayout.widget.ConstraintLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jieli.bt.att.R
import com.jieli.bt.att.util.FileUtil
import java.io.File

/**
 * LogFileAdapter
 * @author zqjasonZhong
 * @since 2024/11/7
 * @email zhongzhuocheng@zh-jieli.com
 * @desc 日志文件适配器
 */
class LogFileAdapter : BaseQuickAdapter<File, BaseViewHolder>(R.layout.item_log_file) {

    init {
        addChildClickViewIds(R.id.btn_share, R.id.btn_download, R.id.btn_remove)
    }

    override fun convert(holder: BaseViewHolder, item: File) {
        holder.setText(R.id.tv_file_name, item.name)
        holder.setText(R.id.tv_file_size, FileUtil.formatFileSize(item.length()))
        holder.setImageResource(
            R.id.btn_download, if (FileUtil.isFileInDownload(context, item.name)) {
                R.drawable.ic_downloaded_green
            } else {
                R.drawable.ic_download_blue
            }
        )
        holder.getView<ConstraintLayout>(R.id.cl_content).setOnClickListener { v ->
            getOnItemClickListener()?.onItemClick(this@LogFileAdapter, v, getItemPosition(item))
        }
    }

    fun updateItemByFilePath(filePath: String) {
        val file = getItemByFilePath(filePath) ?: return
        notifyItemChanged(getItemPosition(file))
    }

    private fun getItemByFilePath(filePath: String): File? {
        for (file in data) {
            if (file.path == filePath) {
                return file
            }
        }
        return null
    }
}